//
//  main.cpp
//  jsonRecv
//
//  Created by CmST0us on 16/7/10.
//  Copyright © 2016年 广州睿航电子科技有限公司. All rights reserved.
//

#include <iostream>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <json/json.h>
using namespace std;
int main(int argc, const char * argv[]) {
    struct sockaddr_in udpServerAddr = {0};
    udpServerAddr.sin_addr.s_addr = inet_addr("0.0.0.0");
    udpServerAddr.sin_port = htons(13000);
    udpServerAddr.sin_family = AF_INET;
    
    int udpServerSocket = socket(PF_INET, SOCK_DGRAM, 0);
    if (udpServerSocket < 0) {
        perror("创建套接字失败\n");
        return -1;
    }
    
    if (::bind(udpServerSocket, (struct sockaddr*)&udpServerAddr, sizeof(udpServerAddr)) != 0) {
        perror("绑定失败!\n");
        return -1;
    }
    
    while (1) {
        struct sockaddr_in udpClientAddr = {0};
        socklen_t udpClientAddrLen;
        char *buffer = (char*)malloc(1500);
        bzero(buffer, 1500);
        ssize_t recvLen = recvfrom(udpServerSocket, buffer, 1500, 0, (struct sockaddr*)&udpClientAddr, &udpClientAddrLen);
        if (recvLen < 0) {
            printf("接受错误");
            continue;
        }
        
        printf(buffer);
        Json::Reader reader;
        Json::Value root;
        if (reader.parse(buffer, root)) {
            
            string type = root["Type"].asString();
            cout<<type<<": {"<<endl;
            Json::Value option = root["Option"];
            string x = option["x"].asString();
            string y = option["y"].asString();
            cout<<"x: "<<x<<","<<endl;
            cout<<"y: "<<y<<"\n}"<<endl;
            
//            char sendData[] = "recv";
            ssize_t sendLen = sendto(udpServerSocket,buffer ,recvLen , 0, (struct sockaddr*)&udpClientAddr, udpClientAddrLen);
            if (sendLen < 0) {
                perror("发送错误");
            }
            
        }

        free(buffer);
        
    }
    
    
    return 0;
}
